package com.castle.fortress.admin.rule.group.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.rule.group.entity.RuleGroupEntity;
import com.castle.fortress.admin.rule.group.dto.RuleGroupDto;
import com.castle.fortress.admin.rule.group.service.RuleGroupService;
import com.castle.fortress.admin.rule.rule.service.RuleService;
import com.castle.fortress.admin.rule.rule.dto.RuleDto;
import com.castle.fortress.admin.utils.Sequence;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;
import javax.servlet.http.HttpServletResponse;
import com.castle.fortress.common.entity.DynamicExcelEntity;
import java.util.List;
import java.util.ArrayList;

/**
 * 规则分组表 控制器
 *
 * @author
 * @since 2025-04-21
 */
@Api(tags="规则分组表管理控制器")
@Controller
public class RuleGroupController {
    @Autowired
    private RuleGroupService ruleGroupService;
    
    @Autowired
    private RuleService ruleService;

    /**
     * 规则分组表的分页展示
     * @param ruleGroupDto 规则分组表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("规则分组表分页展示")
    @GetMapping("/rule/group/ruleGroup/page")
    @ResponseBody
    @RequiresPermissions("rule:group:ruleGroup:pageList")
    public RespBody<IPage<RuleGroupDto>> pageRuleGroup(RuleGroupDto ruleGroupDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<RuleGroupDto> page = new Page(pageIndex, pageSize);
        IPage<RuleGroupDto> pages = ruleGroupService.pageRuleGroup(page, ruleGroupDto);

        return RespBody.data(pages);
    }

    /**
     * 规则分组表的列表展示
     * @param ruleGroupDto 规则分组表实体类
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("规则分组表列表展示")
    @GetMapping("/rule/group/ruleGroup/list")
    @ResponseBody
    public RespBody<List<RuleGroupDto>> listRuleGroup(RuleGroupDto ruleGroupDto){
        List<RuleGroupDto> list = ruleGroupService.listRuleGroup(ruleGroupDto);
        return RespBody.data(list);
    }

    /**
     * 规则分组表保存
     * @param ruleGroupDto 规则分组表实体类
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.INSERT)
    @ApiOperation("规则分组表保存")
    @PostMapping("/rule/group/ruleGroup/save")
    @ResponseBody
    @RequiresPermissions("rule:group:ruleGroup:save")
    public RespBody<String> saveRuleGroup(@RequestBody RuleGroupDto ruleGroupDto){
        if(ruleGroupDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        
        // 检查是否存在相同标题的规则分组
        if(ruleGroupDto.getTitle() != null && ruleGroupService.existsByTitle(ruleGroupDto.getTitle())){
            return RespBody.fail("已存在相同标题的规则分组");
        }
        
        RuleGroupEntity ruleGroupEntity = ConvertUtil.transformObj(ruleGroupDto,RuleGroupEntity.class);
        //生成主键id
        ruleGroupEntity.setId(Sequence.getInstance().nextId());
        if(ruleGroupService.save(ruleGroupEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 规则分组表编辑
     * @param ruleGroupDto 规则分组表实体类
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("规则分组表编辑")
    @PostMapping("/rule/group/ruleGroup/edit")
    @ResponseBody
    @RequiresPermissions("rule:group:ruleGroup:edit")
    public RespBody<String> updateRuleGroup(@RequestBody RuleGroupDto ruleGroupDto){
        if(ruleGroupDto == null || ruleGroupDto.getId() == null || ruleGroupDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        RuleGroupEntity ruleGroupEntity = ConvertUtil.transformObj(ruleGroupDto,RuleGroupEntity.class);
        if(ruleGroupService.updateById(ruleGroupEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 规则分组表删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("规则分组表删除")
    @PostMapping("/rule/group/ruleGroup/delete")
    @ResponseBody
    @RequiresPermissions("rule:group:ruleGroup:delete")
    public RespBody<String> deleteRuleGroup(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        
        // 先删除与规则分组关联的规则
        ruleService.removeByScenarioId(id);
        
        // 再删除规则分组
        if(ruleGroupService.removeById(id)) {
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 规则分组表批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("规则分组表批量删除")
    @PostMapping("/rule/group/ruleGroup/deleteBatch")
    @ResponseBody
    @RequiresPermissions("rule:group:ruleGroup:deleteBatch")
    public RespBody<String> deleteRuleGroupBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        
        // 先删除与规则分组关联的规则
        ruleService.removeByScenarioIds(ids);
        
        // 再删除规则分组
        if(ruleGroupService.removeByIds(ids)) {
            return RespBody.data("删除成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 规则分组表详情
     * @param id 规则分组表id
     * @return
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("规则分组表详情")
    @GetMapping("/rule/group/ruleGroup/info")
    @ResponseBody
    @RequiresPermissions("rule:group:ruleGroup:info")
    public RespBody<RuleGroupDto> infoRuleGroup(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        RuleGroupEntity ruleGroupEntity = ruleGroupService.getById(id);
        RuleGroupDto ruleGroupDto = ConvertUtil.transformObj(ruleGroupEntity,RuleGroupDto.class);

        return RespBody.data(ruleGroupDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/rule/group/ruleGroup/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<RuleGroupDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<RuleGroupDto> list = ruleGroupService.listRuleGroup(dynamicExcelEntity.getDto());
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}

    /**
     * 根据规则分组标题获取规则列表
     * @param title 规则分组标题
     * @return 规则列表
     */
    @CastleLog(operLocation="规则分组表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("根据规则分组标题获取规则列表")
    @GetMapping("/rule/group/ruleGroup/getRulesByTitle")
    @ResponseBody
    public RespBody<List<RuleDto>> getRulesByTitle(@RequestParam String title) {
        if (Strings.isEmpty(title)) {
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        
        // 1. 根据title查询rule_group表获取id
        RuleGroupDto queryDto = new RuleGroupDto();
        queryDto.setTitle(title);
        List<RuleGroupDto> ruleGroups = ruleGroupService.listRuleGroup(queryDto);
        
        if (ruleGroups == null || ruleGroups.isEmpty()) {
            return RespBody.data(new ArrayList<>());
        }
        
        // 2. 获取第一个匹配的分组ID
        Long scenarioId = ruleGroups.get(0).getId();
        
        // 3. 使用该ID作为scenario_id查询rule表
        RuleDto ruleDto = new RuleDto();
        ruleDto.setScenarioId(scenarioId);
        List<RuleDto> rules = ruleService.listRule(ruleDto);
        
        return RespBody.data(rules);
    }

}
